package com.galleryviewpager.a_paopao;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.galleryviewpager.DensityUtils;
import com.galleryviewpager.R;

/**
 * canvas 的 paint在画线的时候,处的坐标点 对应画笔的宽度的一半的那个点,由此进行两遍的拓展
 */
public class PaoPaoTestView extends View {

    private Context mContext;

    private int mWidth, mHeight;


    private Paint mPaint = new Paint();
    private float triangleWidth;
    private float triangelHeight;

    private Path path = new Path();

    private RectF rectF = new RectF();

    public PaoPaoTestView(Context context) {
        this(context, null);
    }

    public PaoPaoTestView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PaoPaoTestView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;

        TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.PaoPaoTestView, defStyleAttr, 0);

        triangleWidth = typedArray.getDimension(R.styleable.PaoPaoTestView_triangleWidth, DensityUtils.dip2px(mContext, 40));
        triangelHeight = typedArray.getDimension(R.styleable.PaoPaoTestView_triangleHeight, DensityUtils.dip2px(mContext, 30));

        typedArray.recycle();


        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10f);
        mPaint.setAntiAlias(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            mWidth = MeasureSpec.getSize(widthMeasureSpec);
        } else {
            mWidth = DensityUtils.dip2px(mContext, 200);
        }

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            mHeight = MeasureSpec.getSize(heightMeasureSpec);
        } else {
            mHeight = DensityUtils.dip2px(mContext, 150);
        }
        rectF.set(0 + 10, 0 + 10, mWidth - 10, mHeight);

        setMeasuredDimension(mWidth + 80, (int) (mHeight + triangelHeight + 20));
    }

    @Override
    protected void onDraw(Canvas canvas) {

        canvas.drawColor(Color.RED);

        path.addRoundRect(rectF, 30f, 30f, Path.Direction.CW);
        int leftPointX = (int) (mWidth / 2 - triangleWidth / 2);
        path.moveTo(leftPointX, mHeight);
        mPaint.setColor(Color.GREEN);
        path.lineTo(mWidth / 2, mHeight + triangelHeight);
        path.lineTo(mWidth / 2 + triangleWidth / 2, mHeight);
        canvas.drawPath(path, mPaint);

    }
}
